<template>
    <!-- 三级分类全局组件 -->
    <div>
        <Category ref="cat" :switchform="switchform"></Category>

        <el-card style="margin:10px 0px">
            <template v-if="!switchform">
                <el-button type="primary" size="default" icon="Plus" :disabled="!cat['IDc3']"
                    @click="addtype">添加属性</el-button>
                <el-table border style="margin:10px 0px" :data="attrArr">
                    <el-table-column label="序号" type="index" align="center" width="80px"></el-table-column>
                    <el-table-column label="属性名称" width="120px" prop="attrName"></el-table-column>
                    <el-table-column label="属性值名称">
                        <template #="{ row, $index }">
                            <el-tag style="margin:5px" v-for="(item, index) in row.attrValueList" :key="item.id">{{
                                item.valueName }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="120px">
                        <template #="{ row, $index }">
                            <!-- 修改已有属性的按钮 -->
                            <el-button type="primary" size="small" icon="Edit" round
                                @click="editType(row, $index)"></el-button>
                            <el-popconfirm :title="`你确定删除${row.attrName}?`" width="200px"
                                @confirm="deleteItem(row, $index)">
                                <template #reference>
                                    <el-button type="warning" size="small" icon="Delete" round></el-button>
                                </template>
                            </el-popconfirm>
                        </template>
                    </el-table-column>
                </el-table>
            </template>

            <template v-else>
                <el-form :inline="true">
                    <el-form-item label="属性名称">
                        <el-input placeholder="请你输入属性名称" v-model="attrParams.attrName"></el-input>
                    </el-form-item>
                </el-form>
                <el-button type="primary" size="default" icon="Plus" @click="addAttrValue"
                    :disabled="!attrParams.attrName">添加属性值</el-button>
                <el-button type="primary" size="default" @click="cancel">取消</el-button>
                <el-table border style="margin:10px 0px" :data="attrParams.attrValueList">
                    <el-table-column label="序号" width="80px" type="index" align="center"></el-table-column>
                    <el-table-column label="属性值名称">
                        <template #="{ row, $index }">
                            <!-- 聚焦事件待偶想想是否有别的实现方式 -->
                            <el-input v-if="row.elTrans" :ref="(e: any) => inputArr[$index] = e"
                                @blur="blurEv(row, $index)" size="small" placeholder="请你输入属性值名称"
                                v-model="row.valueName"></el-input>
                            <div v-else @click="edit(row, $index)">{{ row.valueName }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column label="属性值操作">
                        <template #="{ row, $index }">
                            <el-button type="primary" size="small" icon="Delete"
                                @click="deleteItem(row, $index)"></el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-button type="primary" size="default" @click="save"
                    :disabled="!(attrParams.attrValueList.length > 0)">保存</el-button>
                <el-button type="primary" size="default" @click="cancel">取消</el-button>
            </template>
        </el-card>

    </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, watch, nextTick } from 'vue'
import { reqAttr, reqAddOrUpdateAttr, reqRemoveAttr } from '@/apis/product/attr/index'
import type { Attr, AttrValue } from '@/apis/product/attr/type'
import { ElMessage } from 'element-plus'
const cat = ref({})
const attrArr = ref<Attr[]>([])
const getAttrList = async () => {
    attrArr.value = []
    const { IDc1, IDc2, IDc3 } = cat.value
    if (!IDc3) return
    let res = await reqAttr(IDc1, IDc2, IDc3)
    attrArr.value = res.data
}
watch(() => cat.value['IDc3'], () => {
    getAttrList()
})

const inputArr = ref<any>([])
const switchform = ref(false)
//收集新增的属性的数据
const attrParams = reactive<Attr>({
    attrName: "",//新增的属性的名字
    attrValueList: [//新增的属性值数组
    ],
    categoryId: '',//三级分类的ID
    categoryLevel: 3,//代表的是三级分类
})
/* 添加属性 */
const addtype = () => {
    switchform.value = !switchform.value
    /* 以下为必要的初始化 */
    Object.assign(attrParams, {
        attrName: "",//新增的属性的名字
        attrValueList: [
        ],
        categoryId: '',//三级分类的ID
        categoryLevel: 3
    })
    inputArr.value = []
    attrParams.categoryId = cat.value['IDc3']
}
/* 取消回退按钮 */
const cancel = () => { switchform.value = !switchform.value }
/* 编辑属性 */
const editType = (row: AttrValue, $index: number) => {
    switchform.value = !switchform.value
    // console.log(row, $index);
    //深拷贝出错的细节问题处理。遇到了数组拷贝赋值
    const deepClonJson = JSON.parse(JSON.stringify(row))
    Object.assign(attrParams, deepClonJson)
}


/* 添加属性值 */
const addAttrValue = () => {
    attrParams.attrValueList.push({
        valueName: '',
        elTrans: true
    })
    nextTick(() => inputArr.value[inputArr.value.length - 1].focus())
}

//input表单聚焦事件
const blurEv = (row: AttrValue, $index: number) => {
    if (row.valueName.trim() === '') {
        ElMessage({ type: 'error', message: '属性值不能为空哦,没做表单校验咱就删掉，请再次添加~' })
        attrParams.attrValueList.splice($index, 1)
        return
    }
    const repeatIndex = attrParams.attrValueList.findIndex(item => { if (item !== row) return item.valueName === row.valueName })
    // console.log('repeat', repeatIndex);
    if (repeatIndex !== -1) {
        ElMessage({ type: 'error', message: '属性值不能出现重复' })
        attrParams.attrValueList.splice(repeatIndex, 1)
    }
    row.elTrans = false
}
/* 元素input与div的v-if 点击切换编辑 */
const edit = (row: AttrValue, $index: number) => {
    row.elTrans = true
    nextTick(() => inputArr.value[$index].focus())
}
//新增与编辑的del按钮功能就直接集成在这一起了
const deleteItem = (row: any, $index: number) => {
    // console.log(row, $index)
    if (!row.id) {
        attrParams.attrValueList.splice($index, 1)
    } else {
        if (row.attrId) { attrParams.attrValueList.splice($index, 1); return }
        reqRemoveAttr(row.id).then(res => {
            if (res.code === 200) { ElMessage({ type: 'success', message: '属性类型删除成功' }) }
            else { ElMessage({ type: 'error', message: '删除失败' }) }
        })
        getAttrList()
    }
}

const save = async () => {
    //发请求
    let res: any = await reqAddOrUpdateAttr(attrParams)
    //添加属性|修改已有的属性已经成功
    if (res.code == 200) {
        //切换场景
        switchform.value = !switchform.value
        ElMessage({
            type: 'success',
            message: attrParams.id ? '修改成功' : '添加成功'
        })
        //获取全部已有的属性与属性值
        getAttrList()
    } else {
        ElMessage({
            type: 'error',
            message: attrParams.id ? '修改失败' : '添加失败'
        })
    }
}


</script>

<style scoped></style>